#include"Engine.h"

namespace Advanced2D{
	Sprite::Sprite(){		
		imageload = false;
		setPosition( 0.0f, 0.0f );
		setVelocity( 0.0f, 0.0f );
		direction = D3DXVECTOR2( 0.0f, 0.0f);

		image = NULL;
		width = 0;
		height = 0;
		animcolumns = 1;

		frametimer = 0;
		framestart = 0;
		movetimer = 16;
		movestart = 0;

		curframe = 0;
		totalframe = 1;
		animdir = 1;

		rotation = 0.0f;
		scaling = 1.0f;
		color = 0xFFFFFFFF;
	}

	Sprite::~Sprite(){
		if(imageload){
			delete image;
		}
	}

	bool Sprite::loadImage( std::string filename, D3DCOLOR transcolor ){
		if(imageload && image != NULL) delete image;

		image = new Texture();
		if(image->load(filename, transcolor )){
			setSize(image->getWidth(), image->getHeight());
			imageload = true;
			return true;
		}
		else return false;		
	}

	void Sprite::setImage(Texture* image){
		this->image = image;
		setHeight(image->getHeight());
		setWidth(image->getWidth());
		this->imageload = false;
	}

	void Sprite::transform(){
		D3DXMATRIX mat;
		D3DXVECTOR2 scale((float)scaling, (float)scaling );
		D3DXVECTOR2 center((float) (width * scaling) / 2, (float) (height * scaling) / 2);
		D3DXVECTOR2 trans = g_camera->transform( getPosition() );

		D3DXMatrixTransformation2D(&mat, NULL, NULL, &scale, &center, rotation, &trans);

		g_engine->getSpriteHandler()->SetTransform(&mat);
	}

	void Sprite::move(){
		if(movetimer > 0 ){
			if(timeGetTime() > (DWORD)(movestart + movetimer)){
				movestart = timeGetTime();

				position.x = position.x + velocity.x * direction.x;
				position.y = position.y + velocity.y * direction.y;
			}
		}
		else{
			position.x = position.x + velocity.x * direction.x;
			position.y = position.y + velocity.y * direction.y;
		}
	}

	void Sprite::animate(){
		if(frametimer > 0){
			if(timeGetTime() > (DWORD)(framestart + frametimer)){
				framestart = timeGetTime();
				
				curframe += animdir;
				if(curframe > totalframe - 1) curframe = 0;
				if(curframe < 0 ) curframe = totalframe - 1;
			}
		}
		else{
			curframe += animdir;
			if(curframe > totalframe - 1) curframe = 0;
			if(curframe < 0 ) curframe = totalframe - 1;
		}
	}

	void Sprite::draw(){
		int fx = (curframe % animcolumns) * width;
		int fy = (curframe / animcolumns) * height;
		RECT srcRect= {fx, fy, fx + width, fy + height};

		transform();
		g_engine->getSpriteHandler()->Draw(image->getTexture(), &srcRect, NULL, NULL, color);
	}
}